//
//  HMHomeController.m
//  HMMarket
//
//  Created by 孙鹏飞 on 2017/5/8.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMHomeController.h"
#import "HMSlideMenu.h"
#import "HomeCollectionViewCell.h"
#import "CycleScrollView.h"
#import "HMOrderController.h"
#import "HMCouponsController.h"
#import "HMSettingAddressController.h"
#import "HMMessageController.h"
#import "HMCartController.h"
#import "HMSearchController.h"
#import "HomeBtn.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "HMProductListViewController.h"
#import "BannerModel.h"
#import "HomeCategory.h"
#import "HMUsualBuyViewController.h"
#import "HMCertificationViewController.h"
#import "HMChangePasswordController.h"
#import "HMLoginController.h"
#import "HMSpecialPriceViewController.h"
#import "HMProductDetailViewController.h"

@interface HMHomeController () <HMSlideMenuDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HomeBtnDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIButton * slideMenuBtn;
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * bannerArray;
@property (nonatomic, strong) NSMutableArray * firstCategory;
@property (nonatomic, strong) NSMutableArray * abannerArray;

@property (nonatomic, strong) HMSlideMenu * slide;
@property (nonatomic, strong) UIView * nodata;
@property (nonatomic, strong) UIImageView * abannerView;

@property (nonatomic, assign) int CarNum;
@property (nonatomic, assign) int NorecevieNum;


@end

@implementation HMHomeController

- (NSMutableArray *)abannerArray
{
    if (_abannerArray == nil) {
        _abannerArray = [NSMutableArray array];
    }
    return _abannerArray;
}

- (UIImageView *)abannerView
{
    if (_abannerView == nil) {
        _abannerView = [[UIImageView alloc] init];
        _abannerView.hidden = YES;
    }
    return _abannerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = kBackGolor;
    [self setupNav];
    [self setupCollectionView];
    [self setupData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:loginNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:loginExit object:nil];
}

- (UIView *)nodata
{
    if (_nodata == nil) {
        _nodata = [[UIView alloc] init];
        _nodata.backgroundColor = kBackGolor;
        _nodata.frame = CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64);
        _nodata.hidden = YES;
        
        UIImageView * icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"default_network"]];
        icon.y = 180 * KEYWIDTH;
        icon.centerX =KWidthSCREEN/2;
        [_nodata addSubview:icon];
        
        UILabel * titleLable = [[UILabel alloc] init];
        titleLable.text = @"网络请求失败";
        titleLable.font = [UIFont boldSystemFontOfSize:17];
        titleLable.textColor = kGrayTextColor;
        titleLable.x = 0;
        titleLable.y = icon.y + icon.height + 16;
        titleLable.size = CGSizeMake(KWidthSCREEN, 20);
        titleLable.textAlignment = NSTextAlignmentCenter;
        [_nodata addSubview:titleLable];
        
        UIButton * reuseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [reuseBtn setTitle:@"重新加载" forState:UIControlStateNormal];
        [reuseBtn setTitleColor:kffffff forState:UIControlStateNormal];
        reuseBtn.backgroundColor = kMainColor;
        reuseBtn.layer.cornerRadius = 5;
        reuseBtn.layer.masksToBounds = YES;
        reuseBtn.y = CGRectGetMaxY(titleLable.frame) + 13;
        reuseBtn.width = 130;
        reuseBtn.height = 40;
        reuseBtn.centerX = KWidthSCREEN / 2;
        [_nodata addSubview:reuseBtn];
        [reuseBtn addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:self.nodata];
    }
    return _nodata;
}

- (void)refreshData
{
    [self setupData];
}

- (void)setupNav
{
    UIButton * slideMenuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    slideMenuBtn.frame = CGRectMake(0, 20, 50, 40);
    [slideMenuBtn setImage:[UIImage imageNamed:@"user"] forState:UIControlStateNormal];
    [slideMenuBtn addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
    [self.CustomNaviBar addSubview:slideMenuBtn];
    self.slideMenuBtn = slideMenuBtn;
    
    UIImageView * titleView = [[UIImageView alloc] init];
    titleView.frame = CGRectMake((KWidthSCREEN - 80) / 2, 32, 80, 23);
    titleView.image = [UIImage imageNamed:@"e"];
    [self.CustomNaviBar addSubview:titleView];
    
    [self.RightBarItem setImage:[UIImage imageNamed:@"nav_-message"] forState:UIControlStateNormal];
    [self.RightBarItem addTarget:self action:@selector(messageBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupData
{
    self.firstCategory = [NSMutableArray array];
    self.bannerArray = [NSMutableArray array];
    self.abannerArray = [NSMutableArray array];
    
    [HttpBaseTool get:kLunboUrl params:nil success:^(id responseObj) {
        self.bannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
        self.nodata.hidden = YES;
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        self.nodata.hidden = NO;
    }];
    
    [HttpBaseTool get:kCategoryUrl2 params:nil success:^(id responseObj) {
        
        HomeCategory * homeModel = [HomeCategory mj_objectWithKeyValues:responseObj[@"data"]];
        self.firstCategory = homeModel.list;
        self.abannerArray = homeModel.banner;
        
        self.nodata.hidden = YES;
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        [self.view addSubview:self.nodata];
        self.nodata.hidden = NO;
    }];
    
    [HttpBaseTool get:kHomeBadge params:@{@"user_tel":[MGAccountTool getTel]} success:^(id responseObj) {
        self.CarNum = [responseObj[@"data"][@"CarNum"] intValue];
        self.NorecevieNum = [responseObj[@"data"][@"NorecevieNum"] intValue];
        
        self.nodata.hidden = YES;
        [DataSingleton sharedPerson].cartNum = responseObj[@"data"][@"CarNum"];
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        [self.view addSubview:self.nodata];
        self.nodata.hidden = NO;
    }];
    
}

- (void)setupCollectionView
{
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([HomeCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"HomeCollectionViewCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:self.collectionView];
}

#pragma mark - collectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.firstCategory.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeCollectionViewCell" forIndexPath:indexPath];
    cell.cate = self.firstCategory[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HMProductListViewController *vc = [[HMProductListViewController alloc] init];
    vc.dataArray = self.firstCategory;
    vc.selectIndex = indexPath.row;
    vc.CarNum = self.CarNum;
    [self.navigationController pushViewController:vc animated:YES];
    NSLog(@"你点击了第%zd个分类",indexPath.item);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView * headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        [headerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        headerView.backgroundColor = [UIColor lightGrayColor];
        
        UIView * topView = [[UIView alloc] init];
        topView.frame = CGRectMake(0, 0, KWidthSCREEN, 0.5);
        topView.backgroundColor = [UIColor grayColor];
        topView.layer.shadowColor = [UIColor grayColor].CGColor;
        topView.layer.shadowOffset = CGSizeMake(1,4);
        topView.layer.shadowOpacity = 0.5;
        topView.layer.shadowRadius = 3;
        [headerView addSubview:topView];
        
        NSMutableArray * viewsArray = [NSMutableArray array];
        for (int i = 0; i < self.bannerArray.count; i++) {
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 1, KWidthSCREEN, 199.5)];
            BannerModel * banner = self.bannerArray[i];
            NSString * imgStr = [NSString stringWithFormat:@"%@%@",kImageUrl,banner.lunbo_url];
            [imageView sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"banner_1"] options:SDWebImageRetryFailed|SDWebImageLowPriority];
            [viewsArray addObject:imageView];
        }
        CycleScrollView *adView =[[CycleScrollView alloc] initWithFrame:CGRectMake(0, 1, KWidthSCREEN, 199.5) animationDuration:3];
        adView.backgroundColor =[UIColor clearColor];
        adView.fetchContentViewAtIndex =^UIView*(NSInteger pageIndex){
            return viewsArray.count>0?viewsArray[pageIndex]:[[UIImageView alloc] init];
        };
        adView.totalPagesCount =^NSInteger(void){
            return viewsArray.count;
        };
        adView.TapActionBlock =^(NSInteger pageIndex){
            //根据广告的type打开不同的界面
            NSLog(@"%ld",pageIndex);
            BannerModel * banner = self.bannerArray[pageIndex];
            if (!banner.url) {
                return ;
            } else {
                HMProductDetailViewController * vc = [[HMProductDetailViewController alloc] init];
                vc.pro_id = banner.url;
                vc.NavigationBarHidden = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
          
        };
        adView.PageControlShowStyle =UIPageControlShowStyleCenter;
        adView.pageControl.pageIndicatorImage=[UIImage imageNamed:@"pagecontrol_hollow"];
        adView.pageControl.currentPageIndicatorImage =[UIImage imageNamed:@"pagecontrol_solid"];
        [headerView addSubview:adView];
        
        HomeBtn * homeBtn = [HomeBtn homeBtn];
        homeBtn.delegate = self;
        homeBtn.frame = CGRectMake(0, CGRectGetMaxY(adView.frame), KWidthSCREEN, 98);
        [headerView addSubview:homeBtn];
        
        if (self.CarNum > 0) {
            homeBtn.cartCount.hidden = NO;
            [homeBtn.cartCount setTitle:[NSString stringWithFormat:@"%d",self.CarNum] forState:UIControlStateNormal];
        } else {
            homeBtn.cartCount.hidden = YES;
        }
        
        if (self.NorecevieNum > 0) {
            homeBtn.orderCount.hidden = NO;
            [homeBtn.orderCount setTitle:[NSString stringWithFormat:@"%d",self.NorecevieNum] forState:UIControlStateNormal];
        } else {
            homeBtn.orderCount.hidden = YES;
        }
        
        UIView * lineView = [[UIView alloc] init];
        lineView.frame = CGRectMake(0, CGRectGetMaxY(homeBtn.frame), KWidthSCREEN, 1);
        lineView.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
        lineView.layer.shadowColor = [UIColor blackColor].CGColor;
        lineView.layer.shadowOffset = CGSizeMake(0,1);
        lineView.layer.shadowOpacity = 0.2;
        lineView.layer.shadowRadius = 1;
        [headerView addSubview:lineView];
       
        
        HomeCategoryAbanner * ababner = self.abannerArray.firstObject;
        self.abannerView.frame = CGRectMake(0, CGRectGetMaxY(lineView.frame), KWidthSCREEN, 115);
        [headerView addSubview:self.abannerView];
        self.abannerView.userInteractionEnabled = YES;
        [self.abannerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(abannerViewClick)]];
        
        if (!ababner.lunbo_url) {
            self.abannerView.hidden = YES;
        } else {
            NSString * imgStr = [NSString stringWithFormat:@"%@%@",kImageUrl,ababner.lunbo_url];
            [self.abannerView sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"placeholder_5"] options:SDWebImageRetryFailed|SDWebImageLowPriority];
            self.abannerView.hidden = NO;
        }
        
        return headerView;
    }
    
    return [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (CGSize){(KWidthSCREEN - 2)/3,115};
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    HomeCategoryAbanner * ababner = self.abannerArray.firstObject;
    if (ababner.lunbo_url) {
        return (CGSize){KWidthSCREEN,413};
    } else {
        return (CGSize){KWidthSCREEN,298};
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (void)messageBtnClick
{
    // 先判断有无存储账号信息
    if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
        HMLoginController * login = [[HMLoginController alloc] init];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    } else {
        MyLog(@"消息中心");
        HMMessageController * vc = [[HMMessageController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)openMenu:(id)sender
{
    HMSlideMenu * slide = [HMSlideMenu showInSuperView:self.view];
    slide.frame = self.view.frame;
    self.slide = slide;
    slide.delegate = self;    
}

#pragma mark - HomeBtnDelegate
- (void)HomeBtn:(HomeBtn *)homeBtn didClickedBtnAtIndex:(int)btnIndex
{
    switch (btnIndex) {
        case 0:{
            MyLog(@"特价菜品");
            HMSpecialPriceViewController *vc = [[HMSpecialPriceViewController alloc] init];
            vc.CarNum = self.CarNum;
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 1:{
            MyLog(@"购物车");
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                HMCartController * vc = [[HMCartController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 2:{
            MyLog(@"待收货");
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                HMOrderController * vc = [[HMOrderController alloc] init];
                vc.pageIndex = 1;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 3:{
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                HMUsualBuyViewController *VC = [[HMUsualBuyViewController alloc] init];
                VC.CarNum = self.CarNum;
                [self.navigationController pushViewController:VC animated:YES];
                MyLog(@"常购菜品");
            }
          
            break;
        }
        default:
            break;
    }
}

#pragma mark - HMSlideMenuDelegate
- (void)HMSlideMenu:(HMSlideMenu *)menu clickIndex:(NSIndexPath *)index
{
    switch (index.row) {
        case 0:{
            [menu hide];
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                MyLog(@"我的订单");
                HMOrderController * vc = [[HMOrderController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 1:{
            [menu hide];
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                MyLog(@"我的优惠卷");
                HMCouponsController * vc = [[HMCouponsController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 2:{
            [menu hide];
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                MyLog(@"地址管理");
                HMSettingAddressController * vc = [[HMSettingAddressController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 3:{
            [menu hide];
            // 先判断有无存储账号信息
            if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
                HMLoginController * login = [[HMLoginController alloc] init];
                UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
                [self.navigationController presentViewController:nav animated:YES completion:nil];
            } else {
                MyLog(@"修改密码");
                HMChangePasswordController * vc = [[HMChangePasswordController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 4:{
            MyLog(@"退出登录");
            [MGAccountTool removeAccount];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginExit" object:nil];
            break;
        }
        default:
            break;
    }
}

- (void)HMSlideMenuDidClickLoginBtn:(HMSlideMenu *)menu
{
    HMLoginController * login = [[HMLoginController alloc] init];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)HMSlideMenu:(HMSlideMenu *)menu clickIcon:(UIImageView *)icon
{
    // 先判断有无存储账号信息
    if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
        HMLoginController * login = [[HMLoginController alloc] init];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        return;
    }
   
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"1");
        // 相机权限
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。
            
            authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
        {
            // 无权限 引导去开启
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请前往设置->隐私->授权应用使用相册权限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                // 一键到达app独立的隐私配置页
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] canOpenURL:url];
                }
            }];
            [alertController addAction:alertAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
                imagePickerController.NavigationBarHideEnabled = NO;
                //判断是否支持摄像机
                BOOL isCameraSupport = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                NSLog(@"SUPPORT CAMERA:%d", isCameraSupport);
                BOOL isRearSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
                NSLog(@"rear support:%d", isRearSupport);
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.showsCameraControls = YES;
                imagePickerController.delegate = self;
                [self presentViewController:imagePickerController animated:YES completion:nil];
            }
            else
            {
                NSLog(@"手机不支持相机");
            }
        }
    }];
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
            if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请前往设置->隐私->授权应用使用相册权限" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    // 一键到达app独立的隐私配置页
                    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] canOpenURL:url];
                    }
                }];
                [alertController addAction:alertAction];
                [self presentViewController:alertController animated:YES completion:nil];
            } else {
                UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
                imagePickerController.NavigationBarHideEnabled = NO;
                imagePickerController.delegate = self;
                imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.allowsEditing = NO;
                [self presentViewController:imagePickerController animated:YES completion:nil];
            }
    }];
    UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIPickerViewDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *imge = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSDictionary *param =@{@"tel":[MGAccountTool getTel]};
    
    [HttpBaseTool post:kHeadImage params:param images:@[imge] imagesName:@[@"photo.jpeg"] success:^(id responseObj) {
        if ([responseObj[@"code"] intValue] == 200) {
            self.slide.iconView.image = imge;
            [HMHUDManager showHUDWithText:@"头像上传成功"];
        } else {
            [HMHUDManager showHUDWithText:@"头像上传失败"];
        }
        } failure:^(NSError *error) {
            [HMHUDManager showHUDWithText:NetWorkError];
        }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //一句代码实现检测更新,很简单哦 （需要在viewDidAppear完成时，再调用改方法。不然在网速飞快的时候，会出现一个bug，就是当前控制器viewDidLoad调用的话，可能当前视图还没加载完毕就需要推出UIAlertAction）
    [self hsUpdateApp];
}

#pragma mark - UICollectionViewDelegate

/**
 *  天朝专用检测app更新
 */
-(void)hsUpdateApp
{
    //2先获取当前工程项目版本号
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    //  NSLog(@"%@",infoDic);
    NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    
    //3从网络获取appStore版本号
    NSError *error;
    NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]] returningResponse:nil error:nil];
    if (response == nil) {
        NSLog(@"你没有连接网络哦");
        return;
    }
    NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"hsUpdateAppError:%@",error);
        return;
    }
    //    NSLog(@"%@",appInfoDic);
    NSArray *array = appInfoDic[@"results"];
    
    if (array.count < 1) {
        NSLog(@"此APPID为未上架的APP或者查询不到");
        return;
    }
    
    NSDictionary *dic = array[0];
    NSString *appStoreVersion = dic[@"version"];
    //打印版本号
    NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersion,appStoreVersion);
    //设置版本号
    currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    if (currentVersion.length==2) {
        currentVersion  = [currentVersion stringByAppendingString:@"0"];
    }else if (currentVersion.length==1){
        currentVersion  = [currentVersion stringByAppendingString:@"00"];
    }
    appStoreVersion = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    if (appStoreVersion.length==2) {
        appStoreVersion  = [appStoreVersion stringByAppendingString:@"0"];
    }else if (appStoreVersion.length==1){
        appStoreVersion  = [appStoreVersion stringByAppendingString:@"00"];
    }
    
    //4当前版本号小于商店版本号,就更新
    if([currentVersion floatValue] < [appStoreVersion floatValue])
    {
        UIAlertController *alercConteoller = [UIAlertController alertControllerWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"检测到新版本(%@),是否更新?",dic[@"version"]] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //此处加入应用在app store的地址，方便用户去更新，一种实现方式如下
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", STOREAPPID]];
            [[UIApplication sharedApplication] openURL:url];
        }];
        UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alercConteoller addAction:actionYes];
        [alercConteoller addAction:actionNo];
        [self presentViewController:alercConteoller animated:YES completion:nil];
    }else{
        // NSLog(@"版本号好像比商店大噢!检测到不需要更新");
    }
}

/**
 * abannerView手势点击
 */
- (void)abannerViewClick
{
    // 先判断有无存储账号信息
    if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
        HMLoginController * login = [[HMLoginController alloc] init];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    } else {
        MyLog(@"我的优惠卷");
        HMCouponsController * vc = [[HMCouponsController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


@end
